package hydrap2p.hubmanager;

import hydrap2p.helper.Utility;
import hydrap2p.hub.HubStatus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TStruct;
import org.apache.thrift.transport.TIOStreamTransport;

public class Persistance {
	private static List<HubStatus> config;
	
	public static void set(List<HubStatus> config)
	{
		Persistance.config=new LinkedList<HubStatus>();
		for (HubStatus status : config)
		{
			HubStatus temp = new HubStatus(status);
			temp.connected=false;
			Persistance.config.add(temp);
		}
		
	}
	public static void save()
	{
		File file = new File(Utility.appendPath(Utility.getUserConfigurationPath(), "hubmanager.cfg"));
		OutputStream output;
		if (!file.getParentFile().isDirectory())
		{
			boolean ret=file.getParentFile().mkdirs();
			if (!ret)
			{
				System.err.println("Could not create configuration directory for HubManager");
				return;
			}
		}
		if (!file.isFile())
		{
			try {
				boolean ret=file.createNewFile();
			} catch (IOException e) {
				
				System.err.println("Could not create configuration for HubManager");
				return;
			}
		}
		try {
			output = new FileOutputStream(file);
		} catch (FileNotFoundException e1) {
			System.err.println("Could not create configuration for HubManager");
			return;
		}

		TProtocol protocol = new TJSONProtocol(new TIOStreamTransport(output));
		for (HubStatus status : config)
		{
			try {
				status.write(protocol);
			} catch (TException e) {
				System.err.println("Error while saving configuration");
			}
		}
	}
	public static List<HubStatus> load()
	{
		List<HubStatus> ret=new LinkedList<HubStatus>();
		InputStream input;
		int available;
		try {
			File file = new File(Utility.appendPath(Utility.getUserConfigurationPath(), "hubmanager.cfg"));
			input = new FileInputStream(file);
			available=input.available();
		} catch (FileNotFoundException e1) {
			return ret;
		} catch (IOException e) {
			return ret;
		}
		TProtocol protocol = new TJSONProtocol(new TIOStreamTransport(input));
		while (available>0)
		{
			HubStatus temp=new HubStatus();
			try {
				temp.read(protocol);
				ret.add(temp);
				available=input.available();				
			} catch (TException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				available=0;
			}
		}
		return ret;
	}
	
}
